# routes_admin_orders.py
from flask import Blueprint, request, jsonify
from flask_login import login_required
from app.extensions import db
from app.models import Order, OrderItem
from app.utils.orders_utils import require_admin, gen_order_no, calc_amount_cents
from datetime import datetime

admin_orders_bp = Blueprint('admin_orders', __name__, url_prefix='/admin/orders')


@admin_orders_bp.route('/create', methods=['POST'])
@login_required
def admin_create_order():
    require_admin()
    data = request.json or {}
    user_id = data.get('user_id')
    items = data.get('items') or []
    if not user_id or not items:
        return jsonify({'ok': False, 'error': 'user_id and items required'}), 400

    amount = calc_amount_cents(items)
    recipient = {
        'recipient_name': data.get('recipient_name', '').strip(),
        'recipient_email': data.get('recipient_email', '').strip(),
        'recipient_phone': data.get('recipient_phone', '').strip(),
        'recipient_address': data.get('recipient_address', '').strip(),
        'recipient_postal_code': data.get('recipient_postal_code', '').strip(),
    }
    for k, v in recipient.items():
        if not v:
            return jsonify({'ok': False, 'error': f'Missing field: {k}'}), 400

    order = Order(
        user_id=user_id,
        amount=amount,
        currency=data.get('currency', 'USD'),
        **recipient
    )
    db.session.add(order)
    db.session.flush()
    for it in items:
        db.session.add(OrderItem(
            order_id=order.id,
            title=it['title'],
            sku=it.get('sku'),
            qty=int(it.get('qty', 1)),
            unit_price=int(it['unit_price_cents'])
        ))
    db.session.commit()

    return jsonify({'ok': True, 'order_id': order.id})
